<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>个人信息</span>
    </div>
    <el-form label-width="80px" :model="userinfo" :rules="userrules" prop="username" ref="userinfoRef">
      <el-form-item label="登录名称:">
        <el-input v-model="userinfo.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="用户名称:" prop="nickname">
        <el-input v-model="userinfo.nickname"></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱:" prop="email">
        <el-input v-model="userinfo.email"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="put">确认提交</el-button>
        <el-button @click="test">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { UserPutApi } from '../../api/user.js'
export default {
  name: 'Username',
  data() {
    return {
      userinfo: {
        ...this.$store.state.user.user
      },
      userrules: {
        username: [
          { required: true, message: '该内容是必填项', trigger: 'blur' },
          { pattern: /^[1-9]\d*$/, message: '该内容是必填项', trigger: 'blur' }
        ],
        nickname: [
          { required: true, message: '该内容是必填项', trigger: 'blur' },
          { pattern: /^\S{1,10}$/, message: '该内容必须是1-10的非空字符串', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '该内容是必填项', trigger: 'blur' },
          { type: 'email', message: '该内容是邮箱格式', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    test() {
      this.$refs.userinfoRef.resetFields()
      this.userinfo = Object.assign({}, this.$store.state.user.user)
    },
    put() {
      this.$refs.userinfoRef.validate(async vali => {
        if (!vali) return
        const { data: res } = await UserPutApi(this.userinfo)
        if (res.code === 0) {
          this.$store.dispatch('user/initUser')
        }
      })
    }
  }
}
</script>

<style lang="less">
.el-form {
  width: 500px;
}
</style>
